package cn.zhxu.toys.captcha.impl;

import cn.zhxu.toys.captcha.Captcha;
import cn.zhxu.toys.util.StringUtils;

/**
 * 验证码实体
 * @author Troy
 */
public class CaptchaBean implements Captcha {

	private String code;
	private long expireTime;
	private int trys;

	@Override
	public String getCode() {
		return code;
	}

	@Override
	public boolean isExpired() {
		return expireTime < System.currentTimeMillis() / 1000;
	}

	@Override
	public int increaseTrys() {
		return ++trys;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public void setExpireTime(long expireTime) {
		this.expireTime = expireTime;
	}

	public void setTrys(int trys) {
		this.trys = trys;
	}

	@Override
	public String serialize() {
		return expireTime + "," + code + "," + trys;
	}

	public static CaptchaBean parse(String str) {
		if (StringUtils.isBlank(str)) {
			return null;
		}
		String[] splits = str.split(",");
		if (splits.length < 2) {
			return null;
		}
		CaptchaBean bean = new CaptchaBean();
		bean.setExpireTime(Long.parseLong(splits[0]));
		bean.setCode(splits[1]);
		if (splits.length >= 3) {
			bean.setTrys(Integer.parseInt(splits[2]));
		}
		return bean;
	}

}
